<template>
  <div style="padding:0px 8px">
    <el-card class="configContainer">
      <div style="display: flex;flex-direction: row;align-items: center">
        <h4 class="card-title"> 成绩管理 </h4>
        <div class="space"/>
      </div>
      <el-divider/>
      <div style="margin: 8px">
        <el-form ref="search" :inline="true" :model="searchForm" class="demo-form-inline" :rules="searchRules">
          <el-form-item label="年级" prop="year">
            <el-select @change="changeGrade(searchForm.year)" v-model="searchForm.year" placeholder="选择年级进行检索">
              <el-option label="七年级" :value="1"/>
              <el-option label="八年级" :value="2"/>
              <el-option label="九年级" :value="3"/>
            </el-select>
          </el-form-item>

          <el-form-item label="班级">
            <el-select v-model="searchForm.classId" placeholder="选择班级进行检索">
              <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id"/>
            </el-select>
          </el-form-item>

          <el-form-item label="性别">
            <el-select v-model="searchForm.sex" placeholder="选择性别检索">
              <el-option label="男" :value="1"/>
              <el-option label="女" :value="2"/>
            </el-select>
          </el-form-item>

          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" clearable placeholder="输入姓名进行搜索"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :icon="Search" @click="search">
              <el-icon>
                <Search/>
              </el-icon>
              搜索
            </el-button>
            <el-button @click="batchOutput" :loading="importLoad" type="success">导出成绩卡</el-button>
            <el-button @click="downloadScore" :loading="importTotalLoad" type="success">导出成绩汇总单</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div style="flex: 1;">

      </div>

      <el-table height="400px" :data="stuList" style="width: 100%;margin-top: 16px;"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column fixed prop="photoUrl" label="照片" width="120">
          <template #default="scope">
            <el-image v-if="scope.row.photoUrl != null" style="width: 56px; height: 56px"
                      :src="`http://127.0.0.1:8090/res/${scope.row.photoUrl}`" fit="cover">
            </el-image>

            <el-image v-else-if="scope.row.sex == 1" style="width: 56px; height: 56px"
                      src="/src/assets/boy.png" fit="cover">
            </el-image>

            <el-image v-else-if="scope.row.sex == 2" style="width: 56px; height: 56px"
                      src="./src/assets/girl.png" fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column fixed prop="name" label="姓名">
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column fixed prop="stuNo" label="学号">
          <template #default="scope">
            {{ scope.row.stuNo }}
          </template>
        </el-table-column>

        <el-table-column prop="cardId" label="身份证号">
          <template #default="scope">
            {{ scope.row.cardId }}
          </template>
        </el-table-column>

        <el-table-column prop="sex" label="性别" width="120">
          <template #default="scope">
            {{ scope.row.sex == 1 ? '男' : '女' }}
          </template>
        </el-table-column>

        <el-table-column prop="year" label="入学年份">
          <template #default="scope">
            {{ scope.row.year }}
          </template>
        </el-table-column>
        <el-table-column prop="className" label="班级">
          <template #default="scope">
            {{ scope.row.className }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="220" label="操作">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showDetail(scope.row.id)">
              <el-icon>
                <View/>
              </el-icon>
              详情
            </el-button>
            <el-button link type="danger" size="small" @click="showSelectOne(scope.row)">
              <el-icon>
                <Edit/>
              </el-icon>
              成绩录入
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- <el-pagination
          style="margin-top: 16px;width: 100%;display: flex;align-items: center;justify-content: center;"
          background layout="prev, pager, next" :total="numOfStu" /> -->

      <el-pagination
          :page-sizes="[10, 20, 50, 100]"
          :page-count="pagecount"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="currentChange"
          style="margin-top: 16px;width: 100%;display: flex;align-items: center;justify-content: center;"
          background layout="total, sizes, prev, pager, next, jumper"/>
    </el-card>
  </div>

  <el-dialog v-model="printDialogVisible" width="30%" title="导出成绩卡">
    <div style="margin: 16px 0px">
      <el-select v-model="outYear" placeholder="选择导出年级" style="width:100%">
        <el-option label="七年级" :value="1"/>
        <el-option label="八年级" :value="2"/>
        <el-option label="九年级" :value="3"/>
      </el-select>
    </div>
    <template #footer>
      <el-button @click="printDialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="importLoad" @click="batchOutput()">确定</el-button>
    </template>
  </el-dialog>


  <el-drawer v-model="drawer" :title="title" size="50%">
    <div>

      <el-card>
        <div style="margin: 8px">
          <el-form ref="search" :inline="true" class="demo-form-inline">
            <el-form-item label="学期">
              <el-select v-model="selectSemester" placeholder="输入学期进行检索">
                <el-option v-for="item in semesterList" :key="item.value" :label="item.text" :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="getStudentExamInfoById">
                <el-icon>
                  <Search/>
                </el-icon>
                搜索
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-collapse accordion>
          <el-collapse-item :arrow="!(item.subItemList!=null&&item.subItemList.length>0)" :class="getClass(!(item.subItemList!=null&&item.subItemList.length>0))" :name="index"
                            v-for="(item,index) in examInfo">
            <template #title>
              <div style="text-align:center;align-items: center;display: flex;padding: 16px 16px;flex-direction: row;width: 100%;">
                <div style="flex: 1.5;" v-if="item.subId!=-1" >{{ item.subName }}</div>
                <div style="flex: 1.5;" v-else >科目未选</div>
                <div style="display: flex;" @click.stop="click(item.topSubItemRes,item.id)" v-if="item.subItemList?.length===0">
                  <div style="flex: 3;">
                    {{
                      item.topSubItemRes?.finalScore != null ? item.topSubItemRes.finalScore.rawScore + " " + item.topSubItemRes.unit : '----'
                    }}
                  </div>
                  <div style="width: 1px;background: #333333;max-height: 60%;margin: 16px 16px;text-align: center"></div>
                    <div style="flex: 1;display: flex;justify-content: center;vertical-align:middle;align-items: center;">
                      <div
                          style="height: 24px;background: limegreen;color: white;border-radius: 8px;width: max-content;padding: 0px 8px;flex: 1;display: flex;justify-content: center;vertical-align:middle;align-items: center;">
                        {{
                          item.topSubItemRes?.finalScore != null ? item.topSubItemRes.finalScore.conversionScore : '----'
                        }}
                      </div>
                  </div>
                </div>
                <div style="flex: 0.3"  v-else>
                </div>
              </div>
            </template>
            <template #default>
            <div @click="click(item2,item.id)" style="align-items: center;display: flex;padding: 16px 16px;flex-direction: row;width: 100%;"
                 v-for="item2 in item.subItemList">
              <div style="flex: 1;">{{ item2.name }}</div>
              <div style="display: flex">
                <div style="flex: 3;">
                  {{ item2.finalScore != null ? item2.finalScore.rawScore + " " + item2.unit : '----' }}
                </div>
                <div style="width: 1px;background: #333333;max-height: 100%;margin: 0px 16px;"></div>
                <div style="flex: 1;text-align: center;display: flex;">
                  <div style="flex: 1;display: flex;justify-content: center;">
                    <div
                        style="background: limegreen;color: white;border-radius: 8px;width: max-content;padding: 0px 8px;">
                      {{ item2.finalScore != null&& item2.finalScore.conversionScore!= null ? item2.finalScore.conversionScore : '----' }}
                    </div>
                  </div>
                </div>
                <div v-if="item.subId==-1" style="flex: 2;display: flex;">
                  <div style="flex: 1;text-align: center;display: flex;align-items: center;">
                    <div style="flex: 1;display: flex;justify-content: flex-end;">
                      <div>选科</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            </template>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>
    <el-dialog v-model="setScoreShow" width="30%" title="上传成绩">
      <div style="margin: 16px 0px">
       <el-input v-model="scoreForm.score"></el-input>
        <el-select v-model="scoreForm.count" placeholder="请选择次数" style="width: 100%;margin-top: 10px">
          <el-option  :key="1" label="第一次" :value="1"/>
          <el-option  :key="2" label="第二次" :value="2"/>
          <el-option  :key="3" label="第三次" :value="3"/>
        </el-select>
      </div>
      <template #footer>
        <el-button @click="setScoreShow = false">取消</el-button>
        <el-button type="primary"  @click="ok()">确定</el-button>
      </template>
    </el-dialog>
  </el-drawer>
  <CompanyText/>
</template>


<script>

import CompanyText from "../../../components/CompanyText.vue";
import {cloneDeep} from 'lodash-es';

export default {
  name: 'ScoreManagePage',
  props: {
    // msg: String
  },
  components: {
    CompanyText
  },
  data() {
    return {
      scoreForm:{},
      load: false,
      setScoreShow: false,
      subId: null,
      editableData: {},
      select: {},
      title: {},
      drawer: false,
      total: null,
      searchForm: {
        year: null,
        classId: null,
        name: null,
        sex: null,
        current: null,
        size: 10,
      },
      classList: [],
      allClass: [],
      upLoad: false,
      importLoad: false,
      importTotalLoad: false,
      fileList: [],
      stuList: [],
      selectSemester: 1,
      examInfo: [],
      electiveSubList: [],
      semesterList: [
        {
          "text": "七年级上期",
          "value": 1
        },
        {
          "text": "七年级下期",
          "value": 2
        },
        {
          "text": "八年级上期",
          "value": 3
        },
        {
          "text": "八年级下期",
          "value": 4
        },
        {
          "text": "九年级上期",
          "value": 5
        },
        {
          "text": "九年级下期",
          "value": 6
        },],
      selects2: [],
      selects3: [],
      year: new Date().getFullYear(),//获取完整的年份(4位)
      rules: {
        name: [{required: true, message: "姓名不能为空！", tigger: 'blur'}],
        stuNo: [{required: true, message: "学号不能为空！", tigger: 'blur'}],
        cardId: [{required: true, message: "身份证号不能为空！", tigger: 'blur'}],
        year: [{required: true, message: "年级不能为空", tigger: 'change', type: "number"},],
        sex: [{required: true, message: "性别不能为空", tigger: 'change'}],
        classId: [{required: true, message: "班级不能为空！", tigger: 'change', type: 'number'},],
      },
      searchRules: {
        year: [{required: true, message: "年级不能为空", tigger: 'change', type: "number"},],
      },
      editRules: {
        name: [{required: true, message: "姓名不能为空！", tigger: 'blur'}],
        stuNo: [{required: true, message: "学号不能为空！", tigger: 'blur'}],
        cardId: [{required: true, message: "身份证号不能为空！", tigger: 'blur'}],
        year: [{required: true, message: "年级不能为空", tigger: 'change', type: "number"},],
        sex: [{required: true, message: "性别不能为空", tigger: 'change'}],
        classId: [{required: true, message: "班级不能为空！", tigger: 'change', type: 'number'},],
      },
      addForm: {
        id: '',
        name: '',
        cardId: '',
        stuNo: '',
        sex: '1',
        year: '',
      },
      multipleSelection: [],
      dialogVisible: false,
      years: [],
      uploadDialogVisible: false,
      addDialogVisible: false,
      form: {
        id: '',
        name: '',
        cardId: '',
        stuNo: '',
        sex: '1',
        year: '',
      },
      file: null,
    }

  },
  created() {
    this.getStuList();
  },
  methods: {
    getClass(bool){
      if (bool){
        return 'row-expand-cover'
      }
    },
    ok() {
      let that = this;
      console.info(that.scoreForm)
      that.$http({
        url: `/score/updateScore`,
        method: 'POST',
        data: that.scoreForm
      }).then((res) => {
        console.log(res);
        that.setScoreShow = false;
        that.getStudentExamInfoById();
      }, (err) => {
        console.log('fail' + err);
      });
    },
    click(item,id){
      console.info(item)
      if(item.finalScore == null){
        this.scoreForm = {
          count: 1,
          score: "",
          itemNo: item.itemNo,
          electiveId: id
        }
      }else {
        this.scoreForm = item.finalScore
      }
      this.scoreForm.stuId = this.select.id;
      this.scoreForm.electiveId = id;
      this.setScoreShow = true;
    },
    cancel(key) {
      delete this.editableData[key];
    },
    edit(key) {
      console.log(key);
      this.editableData[key] = cloneDeep(this.examInfo[key]);
      console.log(this.editableData[key]);
    },
    save(key) {
      console.info("save")
      console.info(this.examInfo[key].subId)
      Object.assign(this.examInfo[key], this.editableData[key]);
      let that = this;
      this.$http.post("/option/selectSub",
          {
            subId: that.examInfo[key].subId,
            stuId: that.select.id,
            electiveSubId: this.editableData[key].electiveSubId,
          }
      ).then(res => {
        if (res.code === 0) {
          that.$message.success(res.userMsg)
          delete that.editableData[key];
          that.getStudentExamInfoById()
        }
      })
    },
    showSelectOne(item) {
      this.select = {...item};
      this.drawer = true;
      this.title = this.select.className + '-' + this.select.name + "-成绩录入";
      this.getStudentExamInfoById();
    },
    del(id) {
      let that = this;
      this.$http.post("/option/del", {
        id: id
      }).then(res => {
        if (res.code === 0) {
          that.$message.success(res.userMsg)
          that.getStudentExamInfoById()
        }
      })
    },
    changeGrade(grade) {
      this.getClassByGrade(grade);
    },
    getAllClass() {
      let that = this;
      this.$http.post('/class/getClassByGrade', {}).then(function (response) {
        console.log('success' + response);
        that.allClass = response.data;
      }).catch(function (error) {
        console.log('error');
      });
    },
    getStudentExamInfoById() {
      let that = this;
      this.$http.post('/student/getStudentExamInfoById', {
        semester: that.selectSemester,
        id: that.select.id
      }).then(function (response) {
        console.log('success' + response);
        that.examInfo = response.data.electiveSubList;
        for (let i = 0; i < examInfo.length; i++) {
          if (that.examInfo[i].subItemList.length > 0) {
            // that.examInfo[i].hasChildren = true;
          }
        }
      }).catch(function (error) {
        console.log('error');
      });
    },
    getClassByGrade(grade) {
      let that = this;
      that.classList = [];
      this.$http.post('/class/getClassByGrade', {
        grade: grade
      }).then(function (response) {
        console.log('success' + response);
        that.classList = response.data;
      }).catch(function (error) {
        console.log('error');
      });
    },
    downloadScore() {
      this.$refs.search.validate(validate => {
        if (validate) {
          this.importTotalLoad = true;
          let that = this;
          this.$http({
            url: "/score/downloadScore",
            method: 'post',
            data: that.searchForm,
            responseType: 'blob'
          }).then((res) => {
            console.log(res);
            const blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"});
            const elink = document.createElement("a");
            elink.download = `成绩汇总单.xlsx`;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
            that.importTotalLoad = false;
          });
        }
      })
    },

    batchOutput() {
      this.$refs.search.validate(validate => {
        if (validate) {
          this.importLoad = true;
          let that = this;
          let data = {...that.searchForm}
          data.size = -1
          this.$http.post('/student/getStudentsInfo',
              data).then(function (response) {
            let outStuList = response.data.records;
            for (let i = 0; i < outStuList.length; i++) {
              console.log(outStuList[i]);
              that.printStuExamInfoById(outStuList[i], data.year);
            }
            that.importLoad = false;
            this.$refs.search.resetField();
          }).catch(function (error) {
            console.log('error');
          });
        }
      })
    },

    printStuExamInfoById(student, year) {
      let yearStr = year + 6 + '年级';
      let that = this;
      this.$http({
        url: "/student/printStuExamInfoById",
        method: 'post',
        data: {
          "id": student.id,
          "year": year
        },
        responseType: 'blob'
      }).then((res) => {
        console.log(res);
        const blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"});
        const elink = document.createElement("a");
        elink.download = student.stuNo + "-" + yearStr + student.cardId + '-' + student.name + `成绩登记卡.docx`;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      });
    },

    onChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]//这一步，是 展示最后一次选择文件
      }

    },
    onBeforeUpload(file) {
      console.info(file.type)
      const isIMAGE = file.type === 'application/vnd.ms-excel'
      if (!isIMAGE) {
        this.$message.error('上传文件只能是.xls,.xlsx格式!')
      }
      return isIMAGE
    },
    uploadFile(param) {
      this.param = param;
      this.file = param.file;
    },
    upFile() {
      if (this.file == null) {
        this.$message({
          type: "warning",
          message: "文件不能为空",
        })
        return;
      }
      this.upLoad = true;
      let that = this;
      let data = new FormData();
      data.append("file", this.file)
      this.$http.post('/student/importStuList', data, {
            onUploadProgress: (progressEvent) => {
              let num = progressEvent.loaded / progressEvent.total * 100 | 0;
              this.param.onProgress({percent: num})     //进度条
            }
          }
      ).then(function (response) {
        console.log('success' + response);
        if (response.code === 0) {
          console.log('success');
          that.$message.success(response.userMsg)
          that.uploadDialogVisible = false;
          that.getStuList();
        }
        that.file = null;
        that.upLoad = false;
        that.fileList = []
      }).catch(function (error) {
        console.log(error)
      });
    },
    getAllYear() {
      this.$http.get("/student/getAllYears").then(res => {
        this.years = res.data
        console.log(this.years)
      }).catch(err => {
        console.log(err)
      })
    },
    search() {
      this.getStuList()
    },
    reset() {
      this.searchForm = {};
      this.getStuList()
    },
    beforeRemove() {
      this.$refs.upload.clearFiles() //清除文件对象
      this.$forceUpdate();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    addStu() {
      let that = this;
      this.$refs.add.validate(validate => {
        if (validate) {
          this.$http.post("/student/saveOrUpdateStu", this.addForm)
              .then(res => {
                this.addDialogVisible = false
                this.getStuList();
                that.$message.success(res.userMsg)
                // this.addForm = {}
                that.$refs.add.resetField();

              })
              .catch(err => {
                console.log(err)
              })
        } else {
          this.$message("请检查输入项！")
        }
      })

    },
    updateStu() {
      this.$refs.edit.validate(validate => {
        if (validate) {
          this.$http.post("/student/saveOrUpdateStu", this.form)
              .then(res => {
                this.dialogVisible = false
                this.getStuList();
                this.message.success(res.userMsg)
                this.$refs.edit.resetField();
              })
              .catch(err => {
                console.log(err)
              })
        }
      })

    },
    getStuList() {
      let that = this;
      this.$http.post('/student/getStudentsInfo', that.searchForm).then(function (response) {
        console.log('success' + response);
        that.stuList = response.data.records;
        that.pagecount = response.data.pages;
        that.total = response.data.total;
        that.current = response.data.current;
      }).catch(function (error) {
        console.log('error');
      });
    },
    showDetail(id) {
      this.$router.push({path: '/pcIndex/stuInfoManage?', query: {stuId: id}});
    },

    currentChange(current) {
      this.searchForm.current = current;
      this.getStuList();
    },

    handleSizeChange(size) {
      this.searchForm.size = size;
      console.info(this.searchForm.size)
      this.getStuList();
    },
  }

}
</script>

<style scoped>
H3,
H4,
span,
p {
  text-align: left;
}

.text-center H4 {
  text-align: center;
}


.el-col {
  /* border-radius: 4px;
    background-color: rgb(74, 74, 74); */
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
  padding: 8px;
}

.card-body {
  padding: 30px;
  display: flex;
  flex-direction: row;
  border-radius: 4px;
  margin: 8px;
  justify-content: space-around;
}

.text-white {
  color: white;
}

.media .el-icon {
  color: white;
}

h3 {
  padding: 0;
  margin: 0;
}

.configContainer {
  margin: 10px 8px;
  padding: 0px;
  /* border: red 1px solid; */
}
/deep/  .row-expand-cover .el-collapse-item__header .el-icon {
  display: none;
}
</style>
